package com.bear.newsset.ui.activity;

import android.os.Bundle;
import androidx.annotation.Nullable;
import android.text.Editable;
import android.widget.ImageView;

import com.bear.newsset.R;
import com.bear.newsset.entity.NewsParamEntity;
import com.bear.newsset.util.SysUtil;
import com.bear.newsset.widget.BaseActivity;
import com.bear.newsset.widget.NewsView;
import com.bear.newsset.widget.SearchView;

/**
 * 搜索页面
 */
public class SearchActivity extends BaseActivity {
    private SearchView svSearch;
    private NewsView nvNews;
    private ImageView ivFinishBtn;
    private NewsParamEntity mParamEntity;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        initData();
        initListener();
    }

    private void initView() {
        svSearch = findViewById(R.id.search_sv_view);
        ivFinishBtn = findViewById(R.id.search_iv_finish_btn);
        nvNews = findViewById(R.id.search_nv_news_view);
    }

    private void initData() {
        //启用搜索
        svSearch.setEnabledSearch( true );
        mParamEntity = new NewsParamEntity();
        mParamEntity.setMainLableId( 1000 );
        requestNewsData( mParamEntity );
        nvNews.getNewsListView().setPullRefreshEnabled( false );
    }

    private void initListener() {
        //关闭页面
        ivFinishBtn.setOnClickListener(v -> finish());

        //搜索键点击事件监听器
        svSearch.setOnEnterListener(v -> {
            //隐藏键盘
            SysUtil.hideKeyboard( v.getContext() );
            //开始搜索
            startSearch();
        });
    }

    /**
     * 开始搜索
     */
    private void startSearch() {
        Editable e = svSearch.getText();
        if( e == null ) return;
        requestNewsData( mParamEntity
                .clean()
                .setKw( e.toString() ));
    }

    /**
     * 请求新闻数据
     * @param paramEntity       新闻参数
     */
    private void requestNewsData(NewsParamEntity paramEntity) {
        nvNews.getNewsListView()
                .setNewsParam( paramEntity )
                .requestNewsData();
    }
}
